#pragma once

#include <iostream>
#include <string>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include "log.hpp"

const int backlog =5;
extern Log lg;

enum
{
    SOCKERR = 1,
    BINDERR = 2,
    LISTENERR
};

class Sock
{
public:
    Sock()
    {
    }
    ~Sock()
    {
    }

public:
    void Socket()
    {
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd_ < 0)
        {
            lg("fatal", "socket create fail errno:%d strerrno:%s", errno, strerror(errno));
            exit(1);//结束进程，而不是函数
        }
        int opt=1;//直接重启，不陷入Time_Wiat状态，无法立即重启
        setsockopt(sockfd_,SOL_SOCKET,SO_REUSEADDR|SO_REUSEPORT,&opt,sizeof(opt));
        lg("Logo","sock creat success");
    }

    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));

        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr=INADDR_ANY;

        socklen_t len = sizeof(local);
        if (bind(sockfd_, (struct sockaddr *)&local, len) < 0)
        {
            lg("fatal", "bind fail errno:%d,strerror:%s\n", errno, strerror(errno));
            exit(BINDERR);
        }
    }

    void Listen() // 变为监听窗口,错了就别玩了
    {
        if (listen(sockfd_, backlog) < 0)
        {
            lg("fatal", "Listen fail errno:%d,strerror:%s\n", errno, strerror(errno));
            exit(LISTENERR);
        }
    }

    int Accpect(string*ip,uint16_t* port)//输出型参数，谁链接的我，对方的端口，ip
    {

        struct sockaddr_in temp;
        socklen_t len=sizeof(temp);
        
        int newfd=accept(sockfd_,(struct sockaddr*)&temp,&len);
        if(newfd<0)
        {
            lg("fatal", "accpect fail errno:%d,strerror:%s\n", errno, strerror(errno));
            return -1;
        }
        
        *port=ntohs(temp.sin_port);
        
        string ipstr=inet_ntoa(temp.sin_addr);
        *ip=ipstr;

        return newfd;
    }

    bool Connect(string& ip,uint16_t port)//服务器的端口，ip
    {
        struct sockaddr_in server;
        bzero(&server,0);
        server.sin_family=AF_INET;
        server.sin_port=htons(port);
        server.sin_addr.s_addr=inet_addr(ip.c_str());

        int ret=connect(sockfd_,(struct sockaddr*)&server,sizeof(server));
        if(ret<0)
        {
            lg("info", "Connect fail errno:%d,strerror:%s\n", errno, strerror(errno));
            return false;
        }
        return true;
    }

    void Close()
    {
        close(sockfd_);
    }

    int Fd()
    {
        return sockfd_;
    }
private:
    int sockfd_;
};